/**
 * 
 */
package com.service.tag;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import com.pub.exception.InitializeException;
import com.pub.i.AttributesI;
import com.pub.i.SourceI;
import com.pub.i.StatusI;
import com.pub.pub.ConfigureFile;
import com.service.api.google.GetKeywordStats;
import com.service.api.google.GoogleServices;
import com.service.i.ConfigureServiceTagI;
import com.service.tag.domain.LogTagRequestGoogle;
import com.service.tag.domain.Tag;
import com.service.tag.domain.TagAttribute;
import com.service.tag.impl.TagImpl;
import com.service.tag.key.TagKey;
import com.service.vo.KeywordVo;

/**
 * @author iling
 *
 */
public class GetTagAttributes 
{
	private static Logger logger ;
	
	private String DBTag;
	
	private String email, password, userAgent, developerToken;
	
	private ConfigureFile configureFile;
	
	private TagImpl tagImpl;
	private GoogleServices googleService;
	
	static
	{
		logger 	= Logger.getLogger(GetTagAttributes.class.getName());
	}

	/**
	 * 
	 */
	public GetTagAttributes() 
	{
		
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) 
	{
		GetTagAttributes service = new GetTagAttributes();

		service.handle(args);
	}

	public void init(String[] args) throws InitializeException
	{
		configureFile 	= new ConfigureFile();
		
		try {
			configureFile.initLog4j();
			configureFile.loadPropertyFile(GetTagAttributes.class.getSimpleName());
			configureFile.loadPropertyFile("google");
			
			DBTag 			= configureFile.getValueStringNotNull(ConfigureServiceTagI.DB_TAG_HOHO);

			email 			= configureFile.getValueStringNotNull(ConfigureServiceTagI.ACCOUNT_EMAIL);
			password		= configureFile.getValueStringNotNull(ConfigureServiceTagI.ACCOUNT_PASSWORD);
			userAgent		= configureFile.getValueStringNotNull(ConfigureServiceTagI.ACCOUNT_USER_AGENT);
			developerToken	= configureFile.getValueStringNotNull(ConfigureServiceTagI.ACCOUNT_DEVELOPERTOKEN);


			logger.info("email : 		" + email);
			logger.info("userAgent : 	" + userAgent);
			logger.info("developerToken : 	" + developerToken);
			
			logger.info("DB tag : " + DBTag);
			
			
			tagImpl			= new TagImpl(DBTag);
			googleService 	= new GoogleServices(email, password, userAgent, developerToken);
		} catch (Exception e) {
			e.printStackTrace();
			throw new InitializeException("Initialize failure.", e);
		}
		
	}
	
	public void handle(String[] args)
	{
		try{
			init(args);
			
			List<Tag> tags = tagImpl.getCustom(" WHERE id NOT IN (SELECT tagId FROM log_tagRequestGoogle) LIMIT 760");
			
			System.out.println("tag================== " + tags.size());
			
			if(tags.size() == 0)
				return;
			
			GetKeywordStats getStats = googleService.getKeywordStatsService();
			
			KeywordVo vo;
			TagKey tagKey;
			TagAttribute tagAttri;
			
			Map<String, KeywordVo> keywords = new HashMap<String, KeywordVo>(tags.size());
			
			// set request keyword list
			for(Tag tag: tags){
				vo = new KeywordVo();
				
				vo.setKeyword(tag.getName());
				
				keywords.put(tag.getName().toLowerCase(), vo);
			}
			
			// set google keyword attributes
			Long globalMonthlySearches;
	    	Long averageMonthlySearches;
	    	
	    	Double competition;
	    	
	    	getStats.getStats(keywords, 0, keywords.size());
	    	
			for(Tag tag: tags){
				vo = keywords.get(tag.getName().toLowerCase());
				
				if(vo != null){
					globalMonthlySearches 	= 0L;
					averageMonthlySearches	= 0L;
					competition				= 0D;
					
					
					if(vo.containsKey(AttributesI.COMPETITION)){
						competition = (Double)vo.get(AttributesI.COMPETITION);
						
						tagKey = new TagKey();
						
						tagKey.setSourceId(SourceI.SOURCE_GOOGLE);
						tagKey.setTagId(tag.getId());
						tagKey.setAttributeId(51);
						
						tagAttri = new TagAttribute();
						
						tagAttri.setAttributeValue(competition.toString());
						tagAttri.setPrimaryKey(tagKey);
						
						tag.putAttribute(tagKey, tagAttri);
					}
					
					if(vo.containsKey(AttributesI.GLOBAL_MONTHLY_SEARCHES)){
						globalMonthlySearches = (Long)vo.get(AttributesI.GLOBAL_MONTHLY_SEARCHES);
						
						tagKey = new TagKey();
						
						tagKey.setSourceId(SourceI.SOURCE_GOOGLE);
						tagKey.setTagId(tag.getId());
						tagKey.setAttributeId(52);
						
						tagAttri = new TagAttribute();
						
						tagAttri.setAttributeValue(globalMonthlySearches.toString());
						tagAttri.setPrimaryKey(tagKey);
						
						tag.putAttribute(tagKey, tagAttri);
					}
					
					if(vo.containsKey(AttributesI.AVERAGE_MONTHLY_SEARCHES)){
						averageMonthlySearches = (Long)vo.get(AttributesI.AVERAGE_MONTHLY_SEARCHES);
						
						tagKey = new TagKey();
						
						tagKey.setSourceId(SourceI.SOURCE_GOOGLE);
						tagKey.setTagId(tag.getId());
						tagKey.setAttributeId(53);
						
						tagAttri = new TagAttribute();
						
						tagAttri.setAttributeValue(averageMonthlySearches.toString());
						tagAttri.setPrimaryKey(tagKey);
						
						tag.putAttribute(tagKey, tagAttri);
					}
				}			
				
			}
			
			//write tag attributes to tag_attributes table of DB.
			tagImpl.insertAttributes(tags);

			LogTagRequestGoogle taglog;
			for(Tag tag: tags){
				taglog = new LogTagRequestGoogle();
				
				taglog.setTagId(tag.getId());
				taglog.setSearchCount(1);
				taglog.setStatus(StatusI.NORMAL);
				
				tagImpl.insertRequestGoogleLog(taglog);
			}
		}catch(Exception e){
			e.printStackTrace();
		}
	}
}
